package com.linkage.jz.bankruptcy.activity.Project;

import android.app.ActionBar;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.linkage.jz.bankruptcy.BankruptcyApp;
import com.linkage.jz.bankruptcy.Consts;
import com.linkage.jz.bankruptcy.R;
import com.linkage.jz.bankruptcy.activity.MainActivity;
import com.linkage.jz.bankruptcy.activity.Person.PersonSettingReadMeActivity;
import com.linkage.jz.bankruptcy.activity.RegistLogin.GetPwdOneActivity;
import com.linkage.jz.bankruptcy.activity.RegistLogin.PhoneLoginActivity;
import com.linkage.jz.bankruptcy.base.BaseActivity;
import com.linkage.jz.bankruptcy.bean.ManagerUserInfo;
import com.linkage.jz.bankruptcy.bean.MyProInfo;
import com.linkage.jz.bankruptcy.fragment.Project.ProManagerListFrgment;
import com.linkage.jz.bankruptcy.fragment.Project.ProManagerSelListFrgment;
import com.linkage.jz.bankruptcy.net.ToastUtil;
import com.linkage.jz.bankruptcy.utils.SPUtils;
import com.linkage.jz.bankruptcy.widget.CreateGroupDialog;
import com.linkage.jz.bankruptcy.widget.CreateUserDialog;
import com.linkage.jz.bankruptcy.widget.PopupMenu;
import com.linkage.jz.bankruptcy.widget.ShapeLoadingDialog;

import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Random;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.Headers;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;


/**
 * A login screen that offers login via email/password.
 */
public  class ManagerSelListActivity extends BaseActivity implements OnClickListener{
    private static final String TAG = PersonSettingReadMeActivity.class.getSimpleName();
    private Button topBtn01, topBtn02;
    private LinearLayout topBtnContainer;
    private ViewPager mViewPager;
    private TabPagerAdapter mPagerAdapter;
    ArrayList<Fragment> fragments = new ArrayList<Fragment>();
    private ShapeLoadingDialog shapeLoadingDialog ;
    private CreateUserDialog createUserDialog;
    private CreateGroupDialog createGroupDialog;
    private static String mProjectID;
    private PopupMenu popupMenu;
    private int  changeType =-1;
    @Override
    public void initData() {

    }

    @Override
    public void setListener() {

        top_back.setOnClickListener(this);
    }

    @Override
    public void initTitle() {
        top_title = findViewById(R.id.top_title);
        top_title.setText("选择人员");
//        top_mune.setVisibility(View.INVISIBLE);
    }

    @Override
    public void initView() {

    }


    TextView top_title;
    Button top_back;
    TextView top_mune;

    public static void start(Context context,String info) {
        mProjectID = info;
        Intent intent = new Intent(context, ManagerSelListActivity.class);
        context.startActivity(intent);

    }

    @Override
    public void onCreate(Bundle savedInstanceState) {

        setContentView(R.layout.activity_sel_pro_managelist);
        ManagerUserInfo info = new ManagerUserInfo();
        BankruptcyApp.getInstance().selManger = info;
        try {
            mProjectID = getIntent().getStringExtra("mProjectID");
        }catch (Exception ex)
        {
            ex.printStackTrace();
        }

        initview();
        shapeLoadingDialog = new ShapeLoadingDialog(this);
        ActionBar bar = this.getActionBar();
        if(bar != null){
            bar.hide();
        }

        init();
        popupMenu = new PopupMenu(this);
        super.onCreate(savedInstanceState);
    }

    //初始化视图
    private void initview() {
        //登录层、下拉层、其它登录方式层



        top_back = findViewById(R.id.top_back);
        top_mune = findViewById(R.id.top_mune);

        top_mune.setVisibility(View.VISIBLE);
        top_mune.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {

                String id ="";
                ManagerUserInfo model =  BankruptcyApp.getInstance().selManger;
                if(BankruptcyApp.getInstance().selManger!=null )
                {
                    id = BankruptcyApp.getInstance().selManger.getId();
                }

                if("".equalsIgnoreCase(id))
                {
                    ToastUtil.showShort("请先选择管理人");
                    return;
                }
                Intent intent = new Intent(ManagerSelListActivity.this, CreateProTalkActivity.class);
                intent.putExtra("seluserName", model.getName());
                intent.putExtra("seluserId", model.getId());
                intent.putExtra("selsysuserId", model.getSysUserId());
                setResult(ManagerSelListActivity.this.RESULT_OK, intent);
                finish();

//                createUserDialog = new CreateUserDialog(ManagerListActivity.this,onClickListener);
//                createUserDialog.show();
//                popupMenu.showLocation(R.id.top_mune);// 设置弹出菜单弹出的位置
//                // 设置回调监听，获取点击事件
//                popupMenu.setOnItemClickListener(new PopupMenu.OnItemClickListener() {
//
//                    @Override
//                    public void onClick(PopupMenu.MENUITEM item, String str) {
//                        // TODO Auto-generated method stub
////                        Toast.makeText(ManagerListActivity.this, str, Toast.LENGTH_LONG).show();
//                        if("添加成员".equalsIgnoreCase(str))
//                        {
//                            changeType=1;
//                            createUserDialog = new CreateUserDialog(ManagerSelListActivity.this,onClickListener);
//                            createUserDialog.show();
//                        }else{
//                            changeType=2;
//                            createGroupDialog = new CreateGroupDialog(ManagerSelListActivity.this,onClickListener);
//                            createGroupDialog.show();
//                        }
//                    }
//                });

            }
        });
    }

    private OnClickListener onClickListener = new OnClickListener() {
        @Override
        public void onClick(View v) {

            switch (v.getId()) {

                case R.id.btn_chancel_g:
                    createGroupDialog.dismiss();
                    break;
                case R.id.btn_save_g:
                    String name = createGroupDialog.text_name_g.getText().toString().trim();
                    addGroup(name);
                    break;

            }
        }
    };



    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_login:
                //返回
                MainActivity.start(this);
                finish();
                break;
            case R.id.ll_phonelogin:
                PhoneLoginActivity.start(this);
                finish();
                break;
            case R.id.top_back:
                finish();
                break;
            case R.id.getPwd:
                GetPwdOneActivity.start(this);
            case R.id.id_dcphGroup_topBtn01:
                changeFragmentFocus(0);
                mViewPager.setCurrentItem(0);
                break;
            case R.id.id_dcphGroup_topBtn02:
                changeFragmentFocus(1);
                mViewPager.setCurrentItem(1);
                break;
            default:
                break;
        }
    }

    private void init(){
        ProManagerSelListFrgment groupChildrenCollect = new ProManagerSelListFrgment();
//        DocTmpGFrgment groupChildrenHasBuy = new DocTmpGFrgment();
        Bundle bundle = new Bundle();
        bundle.putString("proid",mProjectID);//这里的values就是我们要传的值
        groupChildrenCollect.setArguments(bundle);

        fragments.add(groupChildrenCollect);
//        fragments.add(groupChildrenHasBuy);

        topBtn01 = (Button) this.findViewById(R.id.id_dcphGroup_topBtn01);
        topBtn02 = (Button) this.findViewById(R.id.id_dcphGroup_topBtn02);
        topBtnContainer = (LinearLayout) this.findViewById(R.id.id_dcphGroup_topBtn_container);
        topBtn01.setOnClickListener(this);
        topBtn02.setOnClickListener(this);
        mViewPager = (ViewPager) this.findViewById(R.id.id_dcphGroup_viewPager);
        mPagerAdapter = new TabPagerAdapter(this.getSupportFragmentManager(), fragments);

        mViewPager.setAdapter(mPagerAdapter);
        mViewPager.invalidate();
        mPagerAdapter.notifyDataSetChanged();
    }

    /*
     * 自定义FragmentStatePagerAdapter适配器来显示滑动Fragment
     * */
    private class TabPagerAdapter extends FragmentStatePagerAdapter implements
            ViewPager.OnPageChangeListener {

        private ArrayList<Fragment> objects;

        public TabPagerAdapter(FragmentManager fm, ArrayList<Fragment> objects) {
            super(fm);
            this.objects = objects;
            mViewPager.setOnPageChangeListener(this);
        }

        @Override
        public Fragment getItem(int position) {
            return objects.get(position);
        }

        @Override
        public int getCount() {
            return objects.size();
        }

        @Override
        public void onPageScrollStateChanged(int arg0) {
        }

        @Override
        public void onPageScrolled(int position, float positionOffset,
                                   int positionOffsetPixels) {
        }

        @Override
        public void onPageSelected(int position) {
            //滑动的监听事件
            changeFragmentFocus(position);
        }
    }


    private void changeFragmentFocus(int focus){
        if(focus == 0){
            topBtn01.setBackgroundResource(R.drawable.about_b_corner_btn);
            topBtn02.setBackgroundResource(R.drawable.about_g_corner_btn);
            topBtn01.setTextColor(getResources().getColor(R.color.white));
            topBtn02.setTextColor(getResources().getColor(R.color.text_secondary_color));
        }else if (focus == 1){
            topBtn01.setBackgroundResource(R.drawable.about_g_corner_btn);
            topBtn02.setBackgroundResource(R.drawable.about_b_corner_btn);
            topBtn01.setTextColor(getResources().getColor(R.color.text_secondary_color));
            topBtn02.setTextColor(getResources().getColor(R.color.white));
        }
    }


    public void addGroup(String groupname)
    {
        if(BankruptcyApp.tokeninfo == null|| BankruptcyApp.tokeninfo.getToken() == null)
        {
            return;
        }
        shapeLoadingDialog.setLoadingText("加载中...");
        shapeLoadingDialog.setCanceledOnTouchOutside(false);
        shapeLoadingDialog.show();
        OkHttpClient okHttpClient = new OkHttpClient();
//        HashMap<String, String> params = new HashMap<String, String>();
        Random random = new Random();
        String rom = random.nextLong()+"";
        String timestamp =System.currentTimeMillis()+"";
        String userToken = SPUtils.getInstance(Consts.SPNAME).getString("userToken","");
        String userId = SPUtils.getInstance(Consts.SPNAME).getString("userId","");

        RequestBody requestBody = new FormBody.Builder()
                .add("appid","1000000001")
                .add("nonce",rom)
                .add("timestamp", timestamp)
                .add("token", BankruptcyApp.tokeninfo.getToken())
                .add("userToken",userToken)


                .add("projectId", mProjectID)
                .add("groupName", groupname)
                .build();

        String url = Consts.WEBURL_ADDGROUP;
        Request request = new Request.Builder()
                .url(url)
                .post(requestBody)
                .build();

        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                shapeLoadingDialog.dismiss();
                Log.d(TAG, "onFailure: " + e.getMessage());
                runOnUiThread(new Runnable(){

                    @Override
                    public void run() {
                        //更新UI
                        Toast.makeText(ManagerSelListActivity.this,"保存失败",Toast.LENGTH_SHORT).show();

                    }

                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                Log.d(TAG, response.protocol() + " " +response.code() + " " + response.message());
                Headers headers = response.headers();
                shapeLoadingDialog.dismiss();
                for (int i = 0; i < headers.size(); i++) {
                    Log.d(TAG, headers.name(i) + ":" + headers.value(i));
                }


                String str = response.body().string();
                try{
                    JSONObject object = new JSONObject(str);
                    if(object.optInt("code") == 0)
                    {
                        runOnUiThread(new Runnable() {

                            @Override
                            public void run() {
                                //更新UI
                                Toast.makeText(ManagerSelListActivity.this, "保存成功", Toast.LENGTH_SHORT).show();

                            }

                        });
//                        finish();

                    }else {
                        runOnUiThread(new Runnable() {

                            @Override
                            public void run() {
                                //更新UI
                                Toast.makeText(ManagerSelListActivity.this, "保存失败", Toast.LENGTH_SHORT).show();

                            }

                        });

                    }
                    str = "";
                }catch (Exception ex)
                {
                    ex.printStackTrace();
                    runOnUiThread(new Runnable() {

                        @Override
                        public void run() {
                            //更新UI
                            Toast.makeText(ManagerSelListActivity.this, "保存失败", Toast.LENGTH_SHORT).show();

                        }

                    });
                }
            }
        });
    }

    public void addUser(String groupId,String name,String phone)
    {
        if(BankruptcyApp.tokeninfo == null|| BankruptcyApp.tokeninfo.getToken() == null)
        {
            return;
        }
        shapeLoadingDialog.setLoadingText("加载中...");
        shapeLoadingDialog.setCanceledOnTouchOutside(false);
        shapeLoadingDialog.show();
        OkHttpClient okHttpClient = new OkHttpClient();
//        HashMap<String, String> params = new HashMap<String, String>();
        Random random = new Random();
        String rom = random.nextLong()+"";
        String timestamp =System.currentTimeMillis()+"";
        String userToken = SPUtils.getInstance(Consts.SPNAME).getString("userToken","");
        String userId = SPUtils.getInstance(Consts.SPNAME).getString("userId","");

        RequestBody requestBody = new FormBody.Builder()
                .add("appid","1000000001")
                .add("nonce",rom)
                .add("timestamp", timestamp)
                .add("token", BankruptcyApp.tokeninfo.getToken())
                .add("userToken",userToken)


                .add("projectId", mProjectID)
                .add("groupId", groupId)
                .add("memberName", name)
                .add("memberMobile", phone)
                .build();

        String url = Consts.WEBURL_ADDMEMBER;
        Request request = new Request.Builder()
                .url(url)
                .post(requestBody)
                .build();

        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                shapeLoadingDialog.dismiss();
                Log.d(TAG, "onFailure: " + e.getMessage());
                runOnUiThread(new Runnable(){

                    @Override
                    public void run() {
                        //更新UI
                        Toast.makeText(ManagerSelListActivity.this,"保存失败",Toast.LENGTH_SHORT).show();

                    }

                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                Log.d(TAG, response.protocol() + " " +response.code() + " " + response.message());
                Headers headers = response.headers();
                shapeLoadingDialog.dismiss();
                for (int i = 0; i < headers.size(); i++) {
                    Log.d(TAG, headers.name(i) + ":" + headers.value(i));
                }


                String str = response.body().string();
                try{
                    JSONObject object = new JSONObject(str);
                    if(object.optInt("code") == 0)
                    {
                        runOnUiThread(new Runnable() {

                            @Override
                            public void run() {
                                //更新UI
                                Toast.makeText(ManagerSelListActivity.this, "保存成功", Toast.LENGTH_SHORT).show();

                            }

                        });
//                        finish();

                    }else {
                        runOnUiThread(new Runnable() {

                            @Override
                            public void run() {
                                //更新UI
                                Toast.makeText(ManagerSelListActivity.this, "保存失败", Toast.LENGTH_SHORT).show();

                            }

                        });

                    }
                    str = "";
                }catch (Exception ex)
                {
                    ex.printStackTrace();
                    runOnUiThread(new Runnable() {

                        @Override
                        public void run() {
                            //更新UI
                            Toast.makeText(ManagerSelListActivity.this, "保存失败", Toast.LENGTH_SHORT).show();

                        }

                    });
                }
            }
        });
    }
}


